<template>
  <div class="seller-product-manage">
    <!-- 主要内容区域 -->
    <div class="main-content">
      <div class="content-header">
        <h1>分类管理</h1>
        <p>管理您店铺的商品分类</p>
      </div>

    <div class="content-wrapper">
      <!-- 登录提示 -->
      <div v-if="!isLoggedIn" class="login-prompt">
        <div class="prompt-icon">🔐</div>
        <div class="prompt-text">
          <h3>商家登录后管理分类</h3>
          <p>登录后可以添加、编辑和删除商品分类，更好地管理您的店铺</p>
        </div>
        <div class="prompt-actions">
          <button class="login-btn" @click="goToLogin">商家登录</button>
          <button class="register-btn" @click="goToRegister">注册商家</button>
        </div>
      </div>

      <!-- 添加分类按钮移到列表上方 -->
      <div v-else class="action-bar">
        <button class="btn-primary" @click="showAddDialog = true">
          <i class="icon">➕</i> 添加分类
        </button>
      </div>

      <div v-if="isLoggedIn" class="category-list" v-show="categories.length > 0">
        <div class="category-item" v-for="category in categories" :key="category.categoryId">
          <div class="category-info">
            <span class="category-name">{{ category.categoryName }}</span>
          </div>
          <div class="category-actions">
            <button class="btn-edit" @click="editCategory(category)">
              <i class="icon">✏️</i> 编辑
            </button>
            <button class="btn-delete" @click="deleteCategory(category.categoryId)">
              <i class="icon">🗑️</i> 删除
            </button>
          </div>
        </div>
      </div>

      <div v-if="isLoggedIn" class="empty-state" v-show="!loading && categories.length === 0">
        <div class="empty-icon">🏷️</div>
        <p>暂无分类数据</p>
        <button class="btn-primary" @click="showAddDialog = true">添加分类</button>
      </div>

      <div v-if="isLoggedIn" class="loading-state" v-show="loading">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>
    </div>

    <!-- 添加/编辑分类对话框 -->
    <div class="dialog-overlay" v-if="showAddDialog || showEditDialog" @click="closeDialog">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h3>{{ showAddDialog ? '添加分类' : '编辑分类' }}</h3>
          <button class="dialog-close" @click="closeDialog">×</button>
        </div>
        <div class="dialog-body">
          <div class="form-group">
            <label for="categoryName">分类名称</label>
            <input
              type="text"
              id="categoryName"
              v-model="formData.categoryName"
              placeholder="请输入分类名称"
              maxlength="20"
            />
          </div>
        </div>
        <div class="dialog-footer">
          <button class="btn-cancel" @click="closeDialog">取消</button>
          <button
            class="btn-primary"
            @click="submitForm"
            :disabled="!formData.categoryName.trim()"
          >
            {{ showAddDialog ? '添加' : '更新' }}
          </button>
        </div>
      </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getSellerCategory, addCategory, updateCategory, deleteCategory } from '../api/seller'

export default {
  name: 'SellerCategoryManage',
  data() {
    return {
      categories: [],
      loading: true,
      showAddDialog: false,
      showEditDialog: false,
      formData: {
        categoryName: '',
        categoryId: null
      }
    }
  },
  computed: {
    // 检查商家登录状态
    isLoggedIn() {
      const sellerId = localStorage.getItem('sellerId')
      const sellerToken = localStorage.getItem('sellerToken') || localStorage.getItem('Token')
      return !!(sellerId && sellerToken)
    }
  },
  mounted() {
    // 只有在登录状态下才获取分类数据
    if (this.isLoggedIn) {
      this.fetchCategories()
    }
  },
  methods: {
    async fetchCategories() {
      try {
        this.loading = true
        // 从localStorage获取商家ID
        const sellerId = localStorage.getItem('sellerId')
        if (!sellerId) {
          this.$message.error('请先登录')
          return
        }

        // 调用接口获取分类数据
        const response = await getSellerCategory(sellerId)
        // 后端直接返回数组，不需要访问response.data
        this.categories = response || []
      } catch (error) {
        console.error('获取分类失败:', error)
        // 使用error类型确保消息显示为红色
        this.$message.error('获取分类数据失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },

    editCategory(category) {
      this.formData = {
        categoryName: category.categoryName,
        categoryId: category.categoryId
      }
      this.showEditDialog = true
      this.showAddDialog = false
    },

    async deleteCategory(categoryId) {
      if (confirm('确定要删除这个分类吗？')) {
        try {
          const sellerId = localStorage.getItem('sellerId')
          if (!sellerId) {
            this.$message.error('请先登录')
            return
          }

          // 构造符合CategoryDeleteDTO格式的数据
          const deleteData = {
            id: categoryId,
            sellerId: parseInt(sellerId) // 确保是数字类型
          }

          console.log('删除分类数据:', deleteData)

          // 调用删除接口
            const result = await deleteCategory(deleteData)

            // 根据返回的消息内容决定使用成功（绿色）还是错误（红色）消息类型
            if (result === '删除成功') {
              this.$message.success(result) // 绿色消息
              // 删除成功后刷新列表
              this.fetchCategories()
            } else if (result === '删除失败：该分类下还有商品，无法删除') {
              this.$message.error(result) // 红色消息
            } else {
              this.$message.success(result) // 默认使用成功消息
              this.fetchCategories()
            }
        } catch (error) {
        console.error('删除分类失败:', error)
        this.$message.error(error.message || '删除分类失败，请稍后重试')
      }
      }
    },

    closeDialog() {
      this.showAddDialog = false
      this.showEditDialog = false
      this.resetForm()
    },

    resetForm() {
      this.formData = {
        categoryName: '',
        categoryId: null
      }
    },

    async submitForm() {
      try {
        const sellerId = localStorage.getItem('sellerId')
        if (!sellerId) {
          this.$message.error('请先登录')
          return
        }

        // 准备提交数据
        const categoryName = this.formData.categoryName.trim()
        console.log('分类名称:', categoryName)

        // 确保sellerId是字符串类型，符合后端要求
        const submitData = {
          sellerId: sellerId,
          categoryName: categoryName
        }

        console.log('提交数据:', submitData)

        if (this.showEditDialog) {
          // 实现编辑分类，构造符合CategoryUpdateDTO格式的数据
          const updateData = {
            id: this.formData.categoryId,
            categoryName: categoryName,
            sellerId: parseInt(sellerId) // 确保是数字类型
          }
          console.log('更新分类数据:', updateData)
          await updateCategory(updateData)
        } else {
          // 实现添加分类
          console.log('调用addCategory接口')
          const result = await addCategory(submitData)
          console.log('添加分类结果:', result)
        }

        // 提交成功后关闭对话框并刷新列表
        this.closeDialog()
        this.fetchCategories()
        this.$message.success(this.showEditDialog ? '分类更新成功' : '分类添加成功')
      } catch (error) {
        console.error('提交失败:', error)
        // 使用error类型确保消息显示为红色
        this.$message.error('操作失败，请稍后重试')
      }
    },

    // 跳转到商家登录页面
    goToLogin() {
      this.$router.push('/seller-login')
    },

    // 跳转到商家注册页面
    goToRegister() {
      this.$router.push('/seller-login') // 商家注册通常在登录页面
    }
  }
}
</script>

<style scoped>
.seller-product-manage {
  padding: 20px;
  min-height: 100vh;
 overflow: auto;
  background-color: #f5f5f5;
}

.main-content {
  width: 100%;
}

.content-header {
  margin-bottom: 30px;
  padding: 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  color: white;
  position: relative;
  overflow: hidden;
}

.content-header::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M 10 0 L 0 0 0 10" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="0.5"/></pattern></defs><rect width="100" height="100" fill="url(%23grid)"/></svg>');
  opacity: 0.3;
}

.content-header h1 {
  font-size: 32px;
  color: white;
  margin: 0 0 12px 0;
  font-weight: 700;
  position: relative;
  z-index: 1;
  text-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

.content-header p {
  color: rgba(255, 255, 255, 0.9);
  margin: 0;
  font-size: 16px;
  position: relative;
  z-index: 1;
  opacity: 0.95;
}

.content-wrapper {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.category-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.category-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.category-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.category-info .category-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.category-actions {
  display: flex;
  gap: 10px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-start;
}

/* 按钮样式 */
button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 5px;
}

.btn-primary {
  background-color: #409eff;
  color: white;
}

.btn-primary:hover {
  background-color: #66b1ff;
}

.btn-primary:disabled {
  background-color: #c0c4cc;
  cursor: not-allowed;
}

.btn-edit {
  background-color: #e6a23c;
  color: white;
}

.btn-edit:hover {
  background-color: #ebb563;
}

.btn-delete {
  background-color: #f56c6c;
  color: white;
}

.btn-delete:hover {
  background-color: #f78989;
}

.btn-cancel {
  background-color: #909399;
  color: white;
}

.btn-cancel:hover {
  background-color: #a6a9ad;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #909399;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.empty-state p {
  margin-bottom: 20px;
  font-size: 16px;
}

/* 加载状态样式 */
.loading-state {
  text-align: center;
  padding: 60px 20px;
  color: #909399;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #e0e0e0;
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.dialog-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #909399;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dialog-close:hover {
  color: #606266;
}

.dialog-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-weight: 500;
}

.form-group input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

.form-group input:focus {
  outline: none;
  border-color: #409eff;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px;
  border-top: 1px solid #e0e0e0;
}

/* 登录提示样式 */
.login-prompt {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  max-width: 500px;
  margin: 40px auto;
}

.login-prompt-icon {
  font-size: 64px;
  color: #409eff;
  margin-bottom: 20px;
}

.login-prompt h3 {
  color: #333;
  font-size: 24px;
  margin-bottom: 12px;
  font-weight: 600;
}

.login-prompt p {
  color: #666;
  font-size: 16px;
  margin-bottom: 30px;
  line-height: 1.5;
}

.login-prompt-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
  flex-wrap: wrap;
}

.login-prompt-actions button {
  padding: 12px 24px;
  font-size: 16px;
  border-radius: 6px;
  min-width: 120px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .seller-product-manage {
    padding: 15px;
  }

  .category-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .category-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .action-bar {
    bottom: 20px;
    right: 20px;
  }

  .dialog-content {
    width: 95%;
    margin: 20px;
  }
}
</style>
